///  jh_nine_picture.dart
///
///  Created by iotjin on 2020/09/14.
///  description:  九宫格图片展示 4图处理 加载本地和网络图片

import 'package:common/image/image_tools.dart';
import 'package:flutter/material.dart';

const double _itemSpace = 5.0;
const double _space = 0.0; // 上下左右间距

/// 长按回调，返回当前索引和所有图片数组

class WorldItemPictureWidget extends StatelessWidget {
  const WorldItemPictureWidget(
      {Key? key,
      required this.imageList,
      this.lRSpace = 0.0,
      this.isHandleFour = true,
      this.ignore = true,
      this.maxNum = 9})
      : super(key: key);

  final List imageList;
  final double lRSpace; // 外部设置的左右间距
  final bool isHandleFour;
  final bool ignore; // 忽略一张图片单独显示
  final int maxNum; //  最多显示几个
  @override
  Widget build(BuildContext context) {
    List imgData = imageList;
    if (maxNum != 9) {
      List arr = [];
      for (var i = 0; i < imgData.length; i++) {
        if (i < maxNum) {
          arr.add(imgData[i]);
        }
      }
      imgData = arr;
    }

    var kScreenWidth = MediaQuery.of(context).size.width;

    var ninePictureW = (kScreenWidth - _space * 2 - 2 * _itemSpace - lRSpace) - 12 * 2 + 14 * 2;
    var itemWH = ninePictureW / 3;
    int columnCount = imgData.length > 6
        ? 3
        : imgData.length <= 3
            ? 1
            : 2;
    // print('九宫格宽 $_ninePictureW ');
    // print('item宽  $_itemWH ');
    int total = imgData.length;

    bool isHandleFourNew = isHandleFour && imgData.length == 4;

    var bgWidth = isHandleFourNew ? (_space * 2 + _itemSpace + itemWH * 2) : (kScreenWidth - lRSpace);
    var bgHeight = columnCount * itemWH + _space * 2 + (columnCount - 1) * _itemSpace;
    var crossAxisCount = isHandleFourNew ? 2 : 3;
    var childAspectRatio = 1.0;

    if (total == 1 && ignore == false) {
      bgWidth = (kScreenWidth - lRSpace);
      bgHeight = (kScreenWidth - lRSpace) * (193.0 / 343.0);
      crossAxisCount = 1;
      childAspectRatio = 343.0 / 193.0;
    }
    if (total == 2 && ignore == false) {
      crossAxisCount = 2;
      bgHeight = bgWidth / 2;
    }
    if (total == 4 && ignore == false) {
      bgWidth = (kScreenWidth - lRSpace);
      crossAxisCount = 2;
      bgHeight = bgWidth;
    }

    if (total == 3) {
      bgWidth = (kScreenWidth - lRSpace);
      bgHeight = itemWH * 2 + _itemSpace * 1;
      return SizedBox(
        width: bgWidth,
        height: bgHeight,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
                margin: const EdgeInsets.only(right: _itemSpace),
                width: itemWH * 2 + 0,
                height: itemWH * 2 + _itemSpace,
                child: _itemCell(context, 0)),
            Column(
              children: [
                SizedBox(width: itemWH, height: itemWH, child: _itemCell(context, 1)),
                const SizedBox(height: _itemSpace),
                SizedBox(width: itemWH, height: itemWH, child: _itemCell(context, 2)),
              ],
            )
          ],
        ),
      );
    }
    return SizedBox(
      width: bgWidth,
      height: bgHeight,
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          // 可以直接指定每行（列）显示多少个Item
          crossAxisCount: crossAxisCount, // 一行的Widget数量
          crossAxisSpacing: _itemSpace, // 水平间距
          mainAxisSpacing: _itemSpace, // 垂直间距
          childAspectRatio: childAspectRatio, // 子Widget宽高比例
        ),
        // 禁用滚动事件
        physics: const NeverScrollableScrollPhysics(),
        padding: const EdgeInsets.all(_space), // GridView内边距
        itemCount: imgData.length,
        itemBuilder: (context, index) {
          return _itemCell(context, index);
        },
      ),
    );
  }

  _itemCell(context, index) {
    var img = imageList[index];
    Widget picture = img.startsWith('http')
        ? ImageView(url: img, fit: BoxFit.cover, borderRadius: const BorderRadius.all(Radius.circular(4)))
        : Image.asset(img, fit: BoxFit.cover);

    return GestureDetector(
      child: ConstrainedBox(constraints: const BoxConstraints.expand(), child: picture),
      onTap: () => _clickItemCell(context, index),
    );
  }

  /// 点击cell，展示全图
  _clickItemCell(context, index) {
    PhotoBrowser.show(imagerUrls: imageList, index: index);
  }
}
